package com.feng.financial.common.aspect;

import com.feng.financial.common.exception.ErrorCode;
import com.feng.financial.common.exception.ValidationException;
import com.feng.financial.common.web.WebCommonResponseBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;

/**
 * 控制器controller切面
 * @author Lee
 */
@Aspect
@Component
public class RequestMappingAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(ControllerAdvice.class);

    @Pointcut("execution(* *..*.controller.*Controller.*(..))")
    public void requestMappingPointCut(){}

    @Pointcut(value = "execution(* *..*Service.*(..))")
    public void servicePointCut(){}

    @Around("requestMappingPointCut()")
    public Object requestMappingAdvice(ProceedingJoinPoint joinPoint){
        Signature signature = joinPoint.getSignature();
        Object[] args = joinPoint.getArgs();
        Object response = null;
        String methodLocal = signature.getDeclaringTypeName() + "." + signature.getName();
        LOGGER.info("###{}()###：request：{}", methodLocal,args);
        try {
            response = joinPoint.proceed(args);
            LOGGER.info("###{}()###：response：{}", methodLocal,response);
        } catch (ValidationException e) {
            LOGGER.error("###{}()###：Exception：{}", methodLocal,e.getMessage());
            return  new WebCommonResponseBuilder<Void>()
                    .fail(e.getErrorCode().toString(),e.getMessage())
                    .build();
        }catch (Throwable throwable) {
            throwable.printStackTrace();
            LOGGER.error("###{}()###：Exception：{}", methodLocal,throwable.getMessage());
            return  new WebCommonResponseBuilder<Void>()
                    .fail(ErrorCode.ERROR.getStatusCode(),ErrorCode.ERROR.getStatusDesc())
                    .build();
        }
        return response;
    }

}
